package se.webbzon.oschi01.worldarea;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Timer;
import java.util.TimerTask;

public class DefaultWorldEngineTimer implements WorldEngineTimer {
        
        // A list of all world engines attached to this timer
        private final Collection<WorldEngine> engines;
                
        // Whatever the world is paused or not
        private volatile boolean paused;
        
        /*============================================================
        Constructors
        ============================================================*/
        
        /** Creates a new WorldEngineTimer which executes a global step
         * for all engines attached to this timer every 25ms (approximately). **/
        public DefaultWorldEngineTimer() {
                this(25);
        }
        
        public DefaultWorldEngineTimer(long millis) {
                engines = Collections.synchronizedCollection(new ArrayList<WorldEngine>());
                Timer timer = new Timer();
                timer.schedule(new TimerTaskImpl(), 0, millis);
        }
        
        /*============================================================
        Public Methods
        ============================================================*/
        
        @Override public boolean attachEngine(WorldEngine engine) {
        	return engines.add(engine);
        }
        
        @Override public boolean detachEngine(WorldEngine engine) {
        	return engines.remove(engine);
        }
        
        @Override public void setPaused(boolean paused) {
        	this.paused = paused;
        }

        @Override public boolean getPaused() {
        	return paused;
        }
        
        /*============================================================
        Private Classes
        ============================================================*/

        /** An implementation of a TimerTask. **/
        private final class TimerTaskImpl extends TimerTask {

        	@Override public void run() {
        		if (!paused) synchronized (engines) {
        			for (WorldEngine engine : engines)
        				engine.performStep();
        		}
        	}

        }

}